package com.realshare.bby.service.integral;

import com.realshare.bby.model.*;
import com.realshare.frame.util.DateUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ${DESCRIPTION}
 * author leisure
 * email 15075107120@139.com
 * create 2019-02-21 上午 11:17
 * modify 2019-02-21 上午 11:17
 **/
@Service
public class IntegralReadyData {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SQLManager sqlManager;

    public List<RuleConfigs> getRuleConfigs() {
        return ruleConfigs;
    }

    private List<RuleConfigs> ruleConfigs;


    /**
     * 准备所需要的数据
     */
    public String readyData() {
        log.info("开始准备积分计算所需要的数据");
        try {
            String now = DateUtils.getNowDateTime();
            String sql = "select * from RULE_CONFIGS where STATUS=1 and '%s' >= CONCAT(START_TIME,' 00:00:00') " +
                    "and '%s' <= CONCAT( ifnull(case when length(END_TIME)<=0 then null else END_TIME end, '%s' ),' 59:59:59') " +
                    "order by EXCUTE_INDEX";
            // "and '%s' <= CONCAT(ifnull(END_TIME,'%s'),' 59:59:59') order by EXCUTE_INDEX";
            sql = String.format(sql, now, now, DateUtils.getNowDate());
            ruleConfigs = sqlManager.execute(new SQLReady(sql), RuleConfigs.class);
            for (RuleConfigs configs : ruleConfigs) {
                //查询规则所引用的业务模型以及判断是否正常
                RuleDataModels models = sqlManager.single(RuleDataModels.class, configs.getModelId());
                if (models == null) {
                    return "【" + configs.getName() + "】规则所引用的业务模型未找到";
                }
                if (models.getStatus() == null || models.getStatus() != 1) {
                    return "【" + configs.getName() + "】规则所引用的业务模型【" + models.getName() + "】已失效";
                }
                //查询业务模型数据元
                sql = "select * from RULE_DATA_MODEL_METAS where MODEL_ID = ? ";
                SQLReady sqlReady = new SQLReady(sql, configs.getModelId());
                sqlManager.execute(sqlReady, RuleDataModelMetas.class);
                models.setMetas(sqlManager.execute(sqlReady, RuleDataModelMetas.class));
                configs.setRuleDataModels(models);

                //查询对应业务模型的给分/扣分数据时间列
                configs.setDataTimeMetas(sqlManager.single(RuleDataModelMetas.class, configs.getDataTimeId()));

                //查询给分数据时间列，只有当扣分时才有值
                configs.setGiveDataTimeMetas(sqlManager.single(RuleDataModelMetas.class, configs.getGiveDataTimeId()));

                //查询剩余给分比例列，只有当扣分时才有值
                configs.setResidueRatioIdMetas(sqlManager.single(RuleDataModelMetas.class, configs.getResidueRatioId()));

                //查询给分交易金额列
                configs.setTradeAmountMetas(sqlManager.single(RuleDataModelMetas.class, configs.getTradeAmountId()));

                //查询规则所引用的用户组
                String groupIds = "'" + configs.getGroupIds().replaceAll(",", "','") + "'";
                sql = String.format("select * from RULE_GROUPS where status ='1' and id in(%s)", groupIds);
                List<RuleGroups> ruleGroups = sqlManager.execute(new SQLReady(sql), RuleGroups.class);
                configs.setRuleGroups(ruleGroups);

                //查询增分行为
                sql = "select t1.*,(select max(DATA_TIME) from RULE_INTEGRAL_TASK " +
                        "where RULE_CONFIG_ID='" + configs.getId() + "' and RULE_CONFIG_ACTION_ID=t1.id) LAST_DATA_TIME " +
                        "from RULE_CONFIG_GIVE t1 where t1.CONFIG_ID='" + configs.getId() + "' order by t1.SORT";
                configs.setGives(sqlManager.execute(new SQLReady(sql), RuleConfigGive.class));

                //查询扣分行为
                sql = "select t1.*,(select max(DATA_TIME) from RULE_INTEGRAL_TASK " +
                        "where RULE_CONFIG_ID='" + configs.getId() + "' and RULE_CONFIG_ACTION_ID=t1.id) LAST_DATA_TIME " +
                        "from RULE_CONFIG_DEDUCT t1 where t1.CONFIG_ID='" + configs.getId() + "' order by t1.SORT";
                configs.setDeducts(sqlManager.execute(new SQLReady(sql), RuleConfigDeduct.class));
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return "准备积分计算所需要的数据时出错，错误信息为：【" + e.getMessage() + "】";
        } finally {
            log.info("结束准备积分计算所需要的数据");
        }
    }
}
